package cn.itlight.pet.service.impl;

import cn.itlight.basic.utils.BaiduAuditUtils;
import cn.itlight.pet.domain.Pet;
import cn.itlight.pet.domain.PetDetail;
import cn.itlight.pet.domain.PetOnlineAuditLog;
import cn.itlight.pet.mapper.PetDetailMapper;
import cn.itlight.pet.mapper.PetMapper;
import cn.itlight.pet.mapper.PetOnlineAuditLogMapper;
import cn.itlight.pet.service.IPetService;
import cn.itlight.basic.service.impl.BaseServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author tomliu
 * @since 2022-07-16
 */
@Service
public class PetServiceImpl extends BaseServiceImpl<Pet> implements IPetService {


    @Autowired
    private PetMapper petMapper;

    @Autowired
    private PetDetailMapper petDetailMapper;

    @Autowired
    private PetOnlineAuditLogMapper petOnlineAuditLogMapper;
    @Override
    public void save(Pet pet) {
        // 1.保存宠物
        petMapper.save(pet);
        // 2.设置宠物详情关联宠物
        PetDetail detail = pet.getDetail();
        detail.setPetId(pet.getId());
        // 3.保存宠物详情
        petDetailMapper.save(detail);
    }

    @Override
    public void update(Pet pet) {
        petMapper.update(pet);
        // 2.设置宠物详情关联宠物
        PetDetail detail = pet.getDetail();
        detail.setPetId(pet.getId());
        if(detail.getId() == null){
            petDetailMapper.save(detail);
        } else {
            petDetailMapper.update(detail);
        }
        // 3.保存宠物详情

    }

    @Override
    public void remove(Long id) {

        // 1.删除宠物详情
        petDetailMapper.removeByPetId(id);
        petMapper.remove(id);
    }

    @Override
    public void onsale(List<Long> ids) {

       for (Long id : ids){
           // 1.得到每个宠物基本信息对象
           Pet pet = petMapper.loadById(id);
           StringBuffer sbf = new StringBuffer();
           // 2.调用百度AI进行文字，图片的审核
           if (!BaiduAuditUtils.TextCensor(pet.getName())){
               sbf.append("宠物名称不合法，宠物名称为：" + pet.getName());
           }
           if (sbf.length() > 0){
               // 2.1.如果违规，我们要保存审核失败日志
               PetOnlineAuditLog petOnlineAuditLog = new PetOnlineAuditLog();
               petOnlineAuditLog.setPetId(id);
               petOnlineAuditLog.setNote(sbf.toString());
               petOnlineAuditLogMapper.save(petOnlineAuditLog);
               continue;
           }
           petMapper.onsale(id);
       }

    }

    @Override
    public void offsale(List<Long> ids) {
        petMapper.offsale(ids);
    }

    @Override
    public void batchDel(Long[] ids) {
        petDetailMapper.batchDelByPetId(ids);
        petMapper.batchDel(ids);
    }
}
